package com.example.demo.excel.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.LoginEnity;
import com.example.demo.entity.LoginRole;
import com.example.demo.entity.Person;
import com.example.demo.entity.base.ResponseEntity;
import com.example.demo.entity.excel.UserExcelModel;
import com.example.demo.entity.mybatisplus.TbSysOrganization;
import com.example.demo.entity.mybatisplus.TbSysRole;
import com.example.demo.system.dao.SysOrgDao;
import com.example.demo.system.dao.SysRoleDao;
import com.example.demo.system.service.SystemManageService;
import com.example.demo.util.EmptyUtil;
import com.example.demo.util.SpringContextUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UserImportListener implements ReadListener<UserExcelModel>{
	
	//储存错误提示
	private List<Map<String, String>> errorContext;
	
	private final String ERROR_KEY = "errorTip";
	
	public UserImportListener(List<Map<String, String>> errorContext) {
		super();
		this.errorContext = errorContext;
	}

	@Override
	public void invoke(UserExcelModel data, AnalysisContext context) {
		// TODO Auto-generated method stub
		Integer rowNum = context.readRowHolder().getRowIndex();
		Map<String, String> tableData = new HashMap<>();
		StringBuilder errorStr = new StringBuilder();
		
		log.debug("第{}行解析到一条数据>>{}",rowNum,JSONObject.toJSONString(data));
		
		String login_id = data.getLogin_id();
		String person_name = data.getPerson_name();
		String login_password = data.getLogin_password();
		String phone_no = data.getPhone_no();
		String orgname = data.getOrgname();
		String allow_login = data.getAllow_login();
		String roles = data.getRoles();
		String email = data.getEmail();
		String qqno = data.getQqno();
		String wechatid = data.getWechatid();
		String birth = data.getBirth();
		String addr = data.getAddr();
		
		if(EmptyUtil.isNotEmpty(addr)) {
			birth = birth.replaceAll("/", "-");
		}
		
		LoginEnity loginEntity = new LoginEnity();
		Person person = new Person();
		
		SysOrgDao sysOrgDao = SpringContextUtil.getBean(SysOrgDao.class);
		SysRoleDao sysRoleDao = SpringContextUtil.getBean(SysRoleDao.class);
		SystemManageService systemManageService = SpringContextUtil.getBean(SystemManageService.class);
		
		TbSysOrganization orgParam = new TbSysOrganization();
		orgParam.setOrgname(orgname);
		
		
		try {
			TbSysOrganization org = sysOrgDao.selectOne(new QueryWrapper<TbSysOrganization>(orgParam));
			
			String orgid = org.getOrgid();
			loginEntity.setOrgid(orgid);
		} catch (Exception e) {
			log.error("第{}行组织机构有问题，可能不是系统已录入的组织机构",rowNum,e);
			errorStr.append("第").append(rowNum).append("行组织机构有问题，可能不是系统已录入的组织机构");
			tableData.put(ERROR_KEY, errorStr.toString());
			errorContext.add(tableData);
			return;
		}
		
		List<LoginRole> login_roles = new ArrayList<>();
		
		roles = roles.replaceAll("，", ",");//兼容逗号输入成中文逗号
		String[] roleArr = roles.split(",");
		
		try {
			int roleNum = roleArr.length;
			for (int i = 0; i < roleNum; i++) {
				String roleName = roleArr[i];
				TbSysRole roleParam = new TbSysRole();
				roleParam.setRole_name(roleName);
				TbSysRole sysrole = sysRoleDao.selectOne(new QueryWrapper<TbSysRole>(roleParam));
				String role_id = sysrole.getRole_id();
				LoginRole loginRole = new LoginRole();
				loginRole.setRole_id(role_id);
				login_roles.add(loginRole);
			}
		} catch (Exception e) {
			log.error("第{}行用户角色有问题，可能填写了系统中不存在的角色",rowNum,e);
			errorStr.append("第").append(rowNum).append("行用户角色有问题，可能填写了系统中不存在的角色");
			tableData.put(ERROR_KEY, errorStr.toString());
			errorContext.add(tableData);
			return;
		}
		
		loginEntity.setLogin_id(login_id);
		loginEntity.setLogin_password(login_password);
		loginEntity.setLogin_roles(login_roles);
		switch (allow_login) {
			case "允许":
				loginEntity.setAllow_login(1);
				break;
			case "禁止":
				loginEntity.setAllow_login(0);
				break;
			default:
				loginEntity.setAllow_login(1);
				break;
		}
		person.setPerson_name(person_name);
		person.setPhone_no(phone_no);
		person.setEmail(email);
		person.setQqno(qqno);
		person.setWechatid(wechatid);
		person.setBirth(birth);
		person.setAddr(addr);
		loginEntity.setPerson(person);
		
		ResponseEntity<String> addRet = systemManageService.addUser(loginEntity);
		
		if(200 != addRet.getCode()) {
			errorStr.append("第").append(rowNum).append("行错误信息：").append(addRet.getMsg());
			tableData.put(ERROR_KEY, errorStr.toString());
			errorContext.add(tableData);
			return;
		}
		
		log.debug("第{}行数据录入系统成功",rowNum);
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		// TODO Auto-generated method stub
		log.info("用户导入模板数据录入完成");
	}

}
